﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CaiyinSoft.NetGather.Protocol;

namespace CaiyinSoft.NetGather.NetGatherLib.Publisher
{

    [Serializable]
    public class TextHTMLPublisher : HTMLPublisherBase
    {
        public string SavePath { get; set; }

        public TextHTMLPublisher()
            : base()
        {
            _InitParams();
        }
        private void _InitParams()
        {
            SavePath = "";
        }

        public override void Publish(Dictionary<int, string> HTMLList, IHTMLAnalyzer HTMLAnalyzer )  //List<IHTMLFilter> HTMLFilters)
        {
            if (string.IsNullOrEmpty(SavePath))
                return;

            if (!File.Exists(SavePath))
            {
                File.Create(SavePath).Close();
            }
            //File.Delete(SavePath);


            //StringBuilder sb = new StringBuilder();
            using (StreamWriter sw = new StreamWriter(SavePath, true))
            {
                //foreach (var html in HTMLList)
                //{
                Dictionary<string, List<FilterResult>> analyzerResult = GetAnalyzer(HTMLList, HTMLAnalyzer);
                foreach (var kv in analyzerResult)
                {
                    sw.WriteLine(kv.Key);
                    if (kv.Value == null)
                    {
                        continue;
                    }
                    List<FilterResult> results = kv.Value;
                    results.Sort(FilterResult.Compare);
                    foreach (var res in results)
                    {
                        //byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                        //fs.Write(bytes, 0, bytes.Length);
                        sw.WriteLine(res.HTMLResult);
                        //.AppendFormat("{0}{1}", res.HTMLResult, Environment.NewLine);
                    }
                }
                //}

            }
            
        }

        [NonSerialized]
        private TextHTMLPublisherForm _editform;
        public override InnerFormBase GetEditForm()
        {
            if (_editform == null)
            {
                _editform = new TextHTMLPublisherForm();
                _editform.InfoSaveEventHandler += (sender, args) =>
                {
                    this.SavePath = _editform.SavePath;
                };
            }
            _editform.HTMLPublisher = this;
            return _editform;
        }

    }
}
